<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>新闻列表</title>
</head>
<body>
<h1>新闻列表</h1>
<button id="add">添加新闻</button>
<table id="list">
    <tr>
        <th>序号</th>
        <th>标题</th>
        <th>发布时间</th>
        <th>操作</th>
    </tr>
</table>

<script src="../resources/jquery-2.1.4.js"></script>
<script src="../resources/common.js"></script>
<script>
    $(function (){
        init();
        $("#add").click(function (){
            window.location.href = "newsEdit.html";
        });
    });

    function init() {
        $.ajax({
            url: baseUrl+"/news",
            type: 'GET',
            dataType: 'json',
            success: function (result) {
                console.log(result);
                if (result.code == 0) {
                    var data = result.data;
                    data.forEach(function (item) {
                        var tr = $("<tr></tr>");
                        tr.append($("<td></td>").text(item.id));
                        tr.append($("<td></td>").text(item.title));
                        tr.append($("<td></td>").text(item.gmtCreate));
                        var buttons = $("<td></td>");
                        buttons.append($("<button onclick='view("+item.id+")'></button>").text("查看"));
                        buttons.append($("<button onclick='edit("+item.id+")'></button>").text("编辑"));
                        buttons.append($("<button onclick='del("+item.id+")'></button>").text("删除"));
                        tr.append(buttons);
                        $("#list").append(tr);
                    });
                } else {
                    alert(result.msg);
                }
            }
        });
    }

    function view(id) {
        window.location.href = "newsView.html?id=" + id;
    }

    function edit(id) {
        window.location.href = "newsEdit.html?id=" + id;
    }

    function del(id) {
        var confirmDelete = confirm("是否删除该条新闻?");
        if (confirmDelete) {
            $.ajax({
                url: baseUrl+"/news/" + id,
                type: 'DELETE',
                dataType: 'json',
                success: function (result) {
                    console.log(result);
                    if (result.code == 0) {
                        alert("删除成功");
                        window.location.reload();
                    } else {
                        alert(result.msg);
                    }
                }
            });
        }
    }
</script>
</body>
</html>
